package com.lzx.iteam;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.CcMsgStructure;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.task.DownloadImageTask;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PhotoUtil;
import com.lzx.iteam.util.StringUtil;
import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.ImageLoader;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangshuai on 15-3-11.
 */
public class EditCloudActivity extends Activity implements View.OnClickListener {

    public static final String CLOUD_EDIT_NAME = "name";
    public static final String CLOUD_EDIT_PHONES = "phones";
    public static final String CLOUD_EDIT_CONTACT_ID = "contact_id";
    public static final String CLOUD_EDIT_COMPANY = "compan";
    public static final String CLOUD_EDIT_POSITION = "position";
    public static final String CLOUD_EDIT_EMAIL = "email";
    public static final String CLOUD_EDIT_PHONE = "phone";
    public static final String CLOUD_EDIT_IMAGE = "image";
    public static final String CLOUD_EDIT_SEX = "sex";
//    public static final String CLOUD_EDIT_DEPARTMENT = "department";
    public static final String CLOUD_EDIT_ADDRESS = "address";
    public static final String CLOUD_EDIT_NOTE = "note";
    public static final String CLOUD_LIMIT_PHONE = "limit_phone";
    private static final int PHOTO_PICKED_WITH_DATA = 3781;
    private static final int CAMERA_WITH_DATA = 3784;


    private String mEditName;
    private ArrayList<String> phoneLsit;
    private String mEditPhone;
    private String mEditPhoneFrist;
//    private String mEditPhoneSecond="";
    private String mContactId;
    private String mCurrentId;
    private String mEditImage;
    private String mEditCompany;
    private String mEditPosition;
    private String mEditEmail;
//    private String mEditDepartment;
    private String mEditNote;
    private String mEditAddress;
    private int mEditSex;
    private String mContactSex = "0";
    private File mCurrentPhotoFile;
    private Bitmap imageBitmap;
    private String mImageData;
    private JSONArray array;

    private EditText mName;
    private EditText mPhone;
//    private EditText mPhoneSecond;//第二个电话号码暂时隐藏掉
    private EditText mCompany;
    private EditText mAddress;
//    private EditText mDepartment;
    private EditText mNote;
    private TextView mSex;
    private ToggleButton mShowPhone;
    private RelativeLayout mLimitPhoneLayout;


    private EditText mPosition;
    private EditText mEmail;
    private ImageView mImage;
    private ImageView mImageArrow;
    private FrameLayout mImageLayout;
    private LinearLayout mBack;
    private LinearLayout mComplete;
//    private InputMethodManager imm;
    private ImageLoader mImageLoder;
    private DisplayImageOptions mOptions;
    private DownloadImageTask downloadImageTask;
    private PopupWindow mSetPhotoPop;
    private PopupWindow mSetSexPop;
    private LinearLayout mMainView;
    private RelativeLayout mRlSexLayout;


    public static final String CONTACT_NAME = "contact_name";
    public static final String CONTACT_IMAGE = "contact_image";
    public static final String CONTACT_COMPANY = "contact_company";
    public static final String CONTACT_JOB = "contact_job";
    public static final String CONTACT_EMAIL = "contact_email";
    public static final String CONTACT_PHONE = "contact_phone";
    public static final String CONTACT_LANDLINE = "contact_landline";
//    public static final String CONTACT_DEPARTMENT = "contact_department";
    public static final String CONTACT_ADDRESS = "contact_address";
    public static final String CONTACT_REMARK = "contact_remark";
    public static final String CONTACT_SEX = "contact_sex";
    public static final String SHOW_PHONES = "show_phones";

    private static final int MEG_EDIT = 10086;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MEG_EDIT:
                    if (msg.arg1 == 0) {
                        Toast.makeText(EditCloudActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        EditCloudActivity.this.finish();
                    } else {

                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(EditCloudActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(EditCloudActivity.this, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }

                    }
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cloud_editor_layout);
        initView();
        initProperty();
        getData();
        setData();

    }

    public void initView() {
        mName = (EditText) findViewById(R.id.cloud_contact_name);
        mPhone = (EditText) findViewById(R.id.cloud_contact_phone);
        mPhone.setEnabled(false);
//        mPhoneSecond = (EditText) findViewById(R.id.cloud_contact_phone_second);
        mCompany = (EditText) findViewById(R.id.cloud_contact_company);
        mPosition = (EditText) findViewById(R.id.cloud_contact_position);
        mEmail = (EditText) findViewById(R.id.cloud_contact_email);
        mImage = (ImageView) findViewById(R.id.cloud_contact_photo);
        mImageArrow = (ImageView) findViewById(R.id.iv_image_arrow);
        mComplete = (LinearLayout) findViewById(R.id.cloud_edit_ll_ok);
        mComplete.setOnClickListener(this);
        mImageLayout = (FrameLayout) findViewById(R.id.edit_fl_image);
        mAddress = (EditText) findViewById(R.id.cloud_contact_address);
        mNote = (EditText) findViewById(R.id.cloud_contact_note);
//        mDepartment = (EditText) findViewById(R.id.cloud_contact_department);
        mSex = (TextView) findViewById(R.id.edit_tv_sex);
        mShowPhone = (ToggleButton) findViewById(R.id.tb_limit_phone);
        mLimitPhoneLayout = (RelativeLayout) findViewById(R.id.rl_limit_phone);
        mLimitPhoneLayout.setOnClickListener(this);
        mShowPhone.setChecked(true);
        // 修改头像暂时放弃
//        mImageLayout.setOnClickListener(this);
        mMainView = (LinearLayout) findViewById(R.id.edit_ll_layout);
        mRlSexLayout = (RelativeLayout) findViewById(R.id.edit_rl_sex);
        mRlSexLayout.setOnClickListener(this);
        mBack = (LinearLayout) findViewById(R.id.cloud_btn_back);
        mBack.setOnClickListener(this);
        mImageArrow.setVisibility(View.GONE);

    }

    public void initProperty() {
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        mImageLoder = ImageLoader.getInstance();
//        mOptions = new DisplayImageOptions.Builder()
//                .showStubImage(R.drawable.default_cloud_image)
//                .showImageForEmptyUri(R.drawable.default_cloud_image)
//                .showImageOnFail(R.drawable.default_cloud_image)
//                .cacheInMemory(true)
//                .cacheOnDisc(true)
//                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
//                .bitmapConfig(Bitmap.Config.RGB_565)
//                .build();
    }

    /**
     * 获取数据
     */
    public void getData() {
        Intent data = getIntent();
        mEditName = data.getStringExtra(CLOUD_EDIT_NAME);
        phoneLsit = data.getStringArrayListExtra(CLOUD_EDIT_PHONES);
        mContactId = data.getStringExtra(CLOUD_EDIT_CONTACT_ID);
        mCurrentId = data.getStringExtra(AsynHttpClient.KEY_CURRENT_CONTACT_ID);
        mEditCompany = data.getStringExtra(CLOUD_EDIT_COMPANY);
        mEditPosition = data.getStringExtra(CLOUD_EDIT_POSITION);
        mEditEmail = data.getStringExtra(CLOUD_EDIT_EMAIL);
        mEditPhone = data.getStringExtra(CLOUD_EDIT_PHONE);
        mEditImage = data.getStringExtra(CLOUD_EDIT_IMAGE);
//        mEditDepartment = data.getStringExtra(CLOUD_EDIT_DEPARTMENT);
        mEditAddress = data.getStringExtra(CLOUD_EDIT_ADDRESS);
        mEditNote = data.getStringExtra(CLOUD_EDIT_NOTE);
        mEditSex = data.getIntExtra(CLOUD_EDIT_SEX, 0);
        mContactSex = mEditSex + "";
        setLimitPhone(data.getStringExtra(CLOUD_LIMIT_PHONE));

    }


    /**
     * 设置数据
     */
    public void setData() {
        mName.setText(mEditName);
        if(mEditName.length()>0){
            mName.setSelection(mEditName.length());}
        /*if (phoneLsit != null && phoneLsit.size() > 0 && phoneLsit.size() > 1) {
            mPhone.setText(phoneLsit.get(0));
//            mPhoneSecond.setText(phoneLsit.get(1));
        } else if (phoneLsit != null && phoneLsit.size() > 0) {
            mPhone.setText(phoneLsit.get(0));
        }*/

        if (phoneLsit != null && phoneLsit.size() > 0){
            mPhone.setText(phoneLsit.get(0));
        }

        mCompany.setText(mEditCompany);
        mPosition.setText(mEditPosition);
        mEmail.setText(mEditEmail);
//        mDepartment.setText(mEditDepartment);
        mAddress.setText(mEditAddress);
        mNote.setText(mEditNote);

        if (mEditSex == 0) {
            mSex.setText("未设置");
            mSex.setTextColor(getResources().getColor(R.color.edit_hint));
        } else if (mEditSex == 1) {
            mSex.setText("男");
            mSex.setTextColor(getResources().getColor(R.color.edit_text));
        } else if (mEditSex == 2) {
            mSex.setText("女");
            mSex.setTextColor(getResources().getColor(R.color.edit_text));
        }

//        mImageLoder.displayImage(mEditImage,mImage,mOptions);
        downloadImageTask = new DownloadImageTask(mImage);
        downloadImageTask.execute(mEditImage);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cloud_btn_back:
                finish();
                break;
            case R.id.cloud_contact_company:
                break;
            case R.id.cloud_contact_position:
                break;
            case R.id.cloud_contact_email:
                break;
            case R.id.rl_limit_phone:
                mShowPhone.toggle();
                break;
            case R.id.cloud_edit_ll_ok:
/*
                if (getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
*/
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(EditCloudActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                getUpDateMessage();
                editContactMessage();
                break;
            case R.id.edit_fl_image:
                // 修改头像暂时放弃
                showSetPhotoPop();
                break;
            case R.id.edit_rl_sex:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(EditCloudActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                showSetSexPop();
                break;

        }
    }

    public void getUpDateMessage() {
//        mEditImage = mImageData;
        mEditName = mName.getText().toString().trim();
        mEditCompany = mCompany.getText().toString().trim();
        mEditPosition = mPosition.getText().toString().trim();
        mEditEmail = mEmail.getText().toString().trim();
        mEditPhoneFrist = mPhone.getText().toString().trim();
//        mEditPhoneSecond = mPhoneSecond.getText().toString().trim();
        mEditAddress = mAddress.getText().toString().trim();
//        mEditDepartment = mDepartment.getText().toString().trim();
        mEditNote = mNote.getText().toString().trim();

    }

    /**
     * 发送请求
     */
    public void editContactMessage() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID,
                LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CURRENT_CONTACT_ID, mCurrentId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTACT_ID, mContactId));
        nvps.add(new BasicNameValuePair(CONTACT_NAME, mEditName));
        nvps.add(new BasicNameValuePair(CONTACT_COMPANY, mEditCompany));
        nvps.add(new BasicNameValuePair(CONTACT_JOB, mEditPosition));
        nvps.add(new BasicNameValuePair(CONTACT_EMAIL, mEditEmail));
        nvps.add(new BasicNameValuePair(CONTACT_PHONE, mEditPhoneFrist));
//        nvps.add(new BasicNameValuePair(CONTACT_DEPARTMENT, mEditDepartment));
        nvps.add(new BasicNameValuePair(CONTACT_ADDRESS, mEditAddress));
        nvps.add(new BasicNameValuePair(CONTACT_REMARK, mEditNote));
        nvps.add(new BasicNameValuePair(CONTACT_SEX, mContactSex));
        nvps.add(new BasicNameValuePair(SHOW_PHONES, getLimitPhone() + ""));


        UpdataContactMessage message = new UpdataContactMessage(mHandler.obtainMessage(MEG_EDIT));
        message.mApi = AsynHttpClient.API_CONTACT_UPDATE;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(message);
    }

    class UpdataContactMessage extends CcMsgStructure {

        private Message mmCallback;

        public UpdataContactMessage(Message mmCallback) {
            this.mmCallback = mmCallback;
        }

        @Override
        public void onReceive(JSONObject data) {

            if (mmCallback != null) {
                mmCallback.obj = data;
                mmCallback.sendToTarget();
            }
        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }


    private void setLimitPhone(String limitPhone) {
        if ("0".equals(limitPhone)) {
            mShowPhone.setChecked(false);
        } else if ("1".equals(limitPhone)) {
            mShowPhone.setChecked(true);
        }
    }

    private int getLimitPhone() {//1:显示电话号码(默认),0:隐藏电话号码
        if (mShowPhone.isChecked()) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 选择性别
     */
    public void showSetSexPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.edit_sex_pop_layout, null);
        Button boy = (Button) mainView.findViewById(R.id.edit_sex_boy);
        Button girl = (Button) mainView.findViewById(R.id.edit_sex_girl);
        Button cancel = (Button) mainView.findViewById(R.id.edit_sex_cancle);

        boy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContactSex = "1";
                mSex.setText("男");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        girl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContactSex = "2";
                mSex.setText("女");
                mSex.setTextColor(getResources().getColor(R.color.black));
                mSetSexPop.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSetSexPop.dismiss();
            }
        });

        mSetSexPop = new PopupWindow(this);
        mSetSexPop.setBackgroundDrawable(new BitmapDrawable());
        mSetSexPop.setFocusable(true);
        mSetSexPop.setTouchable(true);
        mSetSexPop.setOutsideTouchable(true);
        mSetSexPop.setContentView(mainView);
        mSetSexPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetSexPop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetSexPop.setAnimationStyle(R.style.bottomStyle);
        mSetSexPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetSexPop.update();

        mainView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mSetSexPop.dismiss();
                return false;
            }
        });

    }

    /**
     * 弹出拍照和从相册选择popwindow
     */
    private void showSetPhotoPop() {
        View mainView = LayoutInflater.from(this).inflate(R.layout.alert_setphoto_menu_layout, null);
        Button btnTakePhoto = (Button) mainView.findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doTakePhoto();
            }
        });
        Button btnCheckFromGallery = (Button) mainView.findViewById(R.id.btn_check_from_gallery);
        btnCheckFromGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
                doPickPhotoFromGallery();
            }
        });
        Button btnCancle = (Button) mainView.findViewById(R.id.btn_cancel);
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSetPhotoPop.dismiss();
            }
        });
        mSetPhotoPop = new PopupWindow(this);
        mSetPhotoPop.setBackgroundDrawable(new BitmapDrawable());
        mSetPhotoPop.setFocusable(true);
        mSetPhotoPop.setTouchable(true);
        mSetPhotoPop.setOutsideTouchable(true);
        mSetPhotoPop.setContentView(mainView);
        mSetPhotoPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mSetPhotoPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mSetPhotoPop.setAnimationStyle(R.style.bottomStyle);
        mSetPhotoPop.showAtLocation(mMainView, Gravity.BOTTOM, 0, 0);
        mSetPhotoPop.update();
    }

    /**
     * 调用系统相机拍照
     */
    protected void doTakePhoto() {
        try {
            // Launch camera to take photo for selected contact
            File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/Photo");
            if (!file.exists()) {
                file.mkdirs();
            }
            mCurrentPhotoFile = new File(file, PhotoUtil.getRandomFileName());
            final Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Constructs an intent for capturing a photo and storing it in a temporary
     * file.
     */
    public static Intent getTakePickIntent(File f) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        return intent;
    }

    /**
     * 剪切图片
     */
    protected void doCropPhoto(File f) {
        try {
            // Add the image to the media store
            MediaScannerConnection.scanFile(this, new String[]{
                    f.getAbsolutePath()
            }, new String[]{
                    null
            }, null);

            // Launch gallery to crop the photo
            final Intent intent = getCropImageIntent(Uri.fromFile(f));
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (Exception e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    private static final int ICON_SIZE = 96;

    /**
     * 获取系统剪裁图片的Intent.
     */
    public static Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra("return-data", true);
        return intent;
    }

    /**
     * 从相册选择图片
     */
    protected void doPickPhotoFromGallery() {
        try {
            // Launch picker to choose photo for selected contact
            final Intent intent = getPhotoPickIntent();
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, R.string.photoPickerNotFoundText, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 获取调用相册的Intent
     */
    public static Intent getPhotoPickIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        intent.putExtra("return-data", true);
        return intent;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_PICKED_WITH_DATA:
                    if (data != null) {

                        imageBitmap = data.getParcelableExtra("data");
                        mImage.setImageBitmap(imageBitmap);
                        byte[] bytes = PhotoUtil.compressImage(imageBitmap);
                        mImageData = StringUtil.compressByteArrayByGzip(bytes);
                    }

                    break;
                case CAMERA_WITH_DATA:
                    doCropPhoto(mCurrentPhotoFile);
                    break;

            }
        }
    }
}
